#!/bin/sh

# Copyright(c) 2011 OpenDomo Services SL. Licensed under GPL v3 or later
# Isidro Catalan <skarvin@gmail.com>


# ----------------------------------------------------------------------------
# desc: Mini file browser
# author: Isidro Catalan <skarvin@gmail.com>, http://www.opendomo.com
# date: October 2008
#
# CHANGES:
#
# ----------------------------------------------------------------------------

# Common video module vars
. "/etc/opendomo/videoConfVars.conf"


# Muestra el contenido de un directorio
showDir ()
{

	DIR_PATH="$1"
	EXT="$2"

	MY_CAMS=""
	for conf_file in `ls $MTN_CNF_PATH/odcam*.conf 2>/dev/null`; do
			# Obtenemos el nombre y la url de streaming de la camara en cuestion
			cam_name=`awk -F" " '/^text_left/ { print $2 }' $conf_file`
			port=`awk -F" " '/^webcam_port/ { print $2 }' $conf_file`   
			MY_CAMS="$MY_CAMS|$cam_name [$port]"
	done

	# TODO: No muy elegante, mejorar rendimiento
	for FILE_NAME in `ls $DIR_PATH`; do
		# Omit the res
  		res=`echo "$DIR_PATH/$FILE_NAME" | grep "odcam"`         
      if [ ! -n "$res" ]; then
			continue
		fi
		
		BASE_NAME=`basename $FILE_NAME`
		short_base_name=`echo $BASE_NAME | cut -c7-10`
		ACCURATE_NAME=`echo $MY_CAMS | tr "|" "\n" | grep "$short_base_name"`
		res=`echo "$DIR_PATH/$FILE_NAME" | grep "$EXT"`

		if [ -n "$res" ] ; then
		   img_name="`basename $WEBSRV_ROOT/images/$BASE_NAME .swf`.jpg"
		   web_img_path="$WEBSRV_ROOT/images/$img_name"

         #TODO: Cambiar a lenguaje CGI!!
         #Shows with thumbnail or not
         if [ "$img_name" != "" ] && [ -f "$DIR_PATH/$img_name" ]; then
   		   ln -s $DIR_PATH/$img_name $web_img_path -f
			   echo "# <a href='/cgi-bin/od.cgi$PATH_INFO?viewfile=$DIR_PATH/$FILE_NAME'><img width='127' height='96' src='/images/$img_name'></a>"
         else
   			echo "# <a href='/cgi-bin/od.cgi$PATH_INFO?viewfile=$DIR_PATH/$FILE_NAME'>$BASE_NAME</a>"
         fi

		elif [ -d "$DIR_PATH/$FILE_NAME" ]; then
			if [ "$ACCURATE_NAME" != "" ]; then
				BASE_NAME="$ACCURATE_NAME"
			fi
			ACCURATE_NAME=""
			echo "#[Dir] <a href='/cgi-bin/od.cgi$PATH_INFO?viewfile=$FILE_NAME'>$BASE_NAME</a>"
		fi		

	done
}


viewFile ()
{
		viewfile=$1
		EXT=$2
      ruta=`getValue "target_dir"`
		file_name=`basename $viewfile`		
		web_path="$WEBSRV_ROOT/images/$file_name"

		# Si es un directorio entramos
		if [ -d $ruta/$viewfile ]; then
		echo "# Mostrando los contenidos del directorio [$viewfile]"
			showDir "$ruta/$viewfile" "$EXT"
		else
		# Si no lo es mostramos el contenido filtrando por extension
			ln -s $viewfile $web_path -f
			echo "
usage frm_show_capture:
	camara	Mostrando captura [$file_name]	video	/images/$file_name
"
		fi
}



